const { Sequelize } = require('sequelize');

// 数据库配置
const sequelize = new Sequelize('lingxi_system', 'root', '888mei525', {
  host: 'localhost',
  dialect: 'mysql',
  timezone: '+08:00',
  logging: false
});

async function testInventoryAPI() {
  try {
    // 测试数据库连接
    await sequelize.authenticate();
    console.log('数据库连接成功');
    
    // 检查产品表结构
    console.log('\n1. 检查products表结构:');
    const [tableStructure] = await sequelize.query('DESCRIBE products');
    console.log('表字段:');
    tableStructure.forEach(field => {
      console.log(`  ${field.Field}: ${field.Type} ${field.Null === 'YES' ? 'NULL' : 'NOT NULL'} ${field.Key} ${field.Default || ''}`);
    });
    
    // 检查当前产品数据
    console.log('\n2. 检查产品数据:');
    const [products] = await sequelize.query('SELECT id, organization_id, sku, name, specification, stock, min_stock, unit FROM products ORDER BY id');
    console.log(`产品总数: ${products.length}`);
    console.log('产品列表:');
    products.forEach(product => {
      console.log(`  ID: ${product.id}, 组织ID: ${product.organization_id}, SKU: ${product.sku}, 名称: ${product.name}, 库存: ${product.stock}, 最低库存: ${product.min_stock}`);
    });
    
    // 检查组织数据
    console.log('\n3. 检查组织数据:');
    const [organizations] = await sequelize.query('SELECT id, name FROM organizations ORDER BY id');
    console.log('组织列表:');
    organizations.forEach(org => {
      console.log(`  ID: ${org.id}, 名称: ${org.name}`);
    });
    
    // 模拟API查询（带组织ID过滤）
    console.log('\n4. 模拟API查询 (organizationId=1):');
    const [filteredProducts] = await sequelize.query(
      'SELECT * FROM products WHERE organization_id = ? ORDER BY created_at DESC LIMIT 20',
      { replacements: [1] }
    );
    console.log(`过滤后产品数: ${filteredProducts.length}`);
    
    // 模拟API查询（不带组织ID过滤）
    console.log('\n5. 模拟API查询 (无组织过滤):');
    const [allProducts] = await sequelize.query(
      'SELECT * FROM products ORDER BY created_at DESC LIMIT 20'
    );
    console.log(`所有产品数: ${allProducts.length}`);
    
    await sequelize.close();
  } catch (error) {
    console.error('操作失败:', error.message);
    if (error.stack) {
      console.error('错误堆栈:', error.stack);
    }
  }
}

// 执行测试
testInventoryAPI();